package com.dominator.socket;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.JsonUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author
 * @ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */

@Component
@ServerEndpoint(value = "/websocket")
@Slf4j
public class WebSocketTools {
    //线程安全的静态变量，表示在线连接数
    private static volatile int onlineCount = 0;

    //用来存放每个客户端对应的WebSocket对象，适用于同时与多个客户端通信
    public static CopyOnWriteArraySet<WebSocketTools> webSocketSet = new CopyOnWriteArraySet<WebSocketTools>();
    //若要实现服务端与指定客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    public static ConcurrentHashMap<Session, Object> webSocketMap = new ConcurrentHashMap<Session, Object>();

    private static RedisUtil ru = RedisUtil.getRu();


    //与某个客户端的连接会话，通过它实现定向推送(只推送给某个用户)
    private Session session;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        webSocketMap.put(session, this); //加入map中
        addOnlineCount();    //
        //--------------群发消息(多用于聊天室场景)
        for (WebSocketTools item : webSocketSet) {
            try {
                this.session.getBasicRemote().sendText ("有新连接加入当前在线人数为" + getOnlineCount());
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session closeSession) {
        webSocketSet.remove(this); //从set中删除
        webSocketMap.remove(closeSession); //从map中删除
        subOnlineCount();          //在线数减1
        //--------------群发消息(多用于聊天室场景)
        for (WebSocketTools item : webSocketSet) {
            try {
                this.session.getBasicRemote().sendText ("有一连接关闭！当前在线人数为" + getOnlineCount());
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message   客户端发送过来的消息
     * @param mySession 可选的参数
     * @throws Exception
     */
    @OnMessage
    public void onMessage(String message, Session mySession) throws Exception {
        log.info("会话sessionId" + mySession.getId() + "来自客户端的消息:" + message);
        sendMessage(message,mySession);
    }


    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        log.info("会话id" + session.getId());

    }


    //给所有客户端发送信息
    public  static void sendAllMessage(String message,Session session) throws IOException {
        session.getBasicRemote().sendText(message);
    }




    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketTools.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketTools.onlineCount--;
    }


    public  static  void  sendMessage(String message,Session mySession){
        try {
            if (mySession.isOpen()) {
                mySession.getBasicRemote().sendText(message);
            } else {
                log.info("会话已经关闭");
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("发送失败" + e.getMessage());
        }
    }

    /**
     * 执行指定的方法
     * @param message
     * @param mySession
     * @return
     */
    public  static  SocketMessage  invokeMethod(String  message,Session mySession) {
        SocketMessage msg = new SocketMessage();
        Dto dto = Dtos.newDto();
        try {
            dto = JsonUtils.toDto(message);
        }catch (Exception e){
            msg = new SocketMessage(ReqEnums.SYS_ERROR, dto.getString("router"),dto.getString("'method"));
        }
        ApiUtils.checkParam(dto,"router,method");
        dto.put("sessionId", mySession.getId());
        try {
            Object object = BeanLoader.getSpringBean(dto.getString("router"));
            Class c = object.getClass();
            Method method= c.getMethod(dto.getString("method"), Dto.class);
            Object resultObj = method.invoke(object, dto);
            if (resultObj instanceof SocketMessage) {
                msg = (SocketMessage) resultObj;
            }
        } catch (ApiException e) {
            msg.setCode(e.getCode());
            msg.setMessage(e.getMessage());
            msg.setRouter(dto.getString("router"));
            msg.setMethod(dto.getString("method"));
        } catch (Exception e) {
            e.printStackTrace();
            msg = new SocketMessage(ReqEnums.SYS_ERROR, dto.getString("router"),dto.getString("'method"));
        } finally {
            return  msg;
        }
    }


    /**
     * 执行指定的方法
     * @param dto
     * @param mySession
     * @return
     */
    public  static  SocketMessage  invokeMethod(Dto dto,Session mySession) {
        SocketMessage msg = new SocketMessage();
        try {
            dto.put("sessionId", mySession.getId());
            Object object = BeanLoader.getSpringBean(dto.getString("router"));
            Class c = object.getClass();
            Method method= c.getMethod(dto.getString("method"), Dto.class);
            Object resultObj = method.invoke(object, dto);
            if (resultObj instanceof SocketMessage) {
                msg = (SocketMessage) resultObj;
            }
        } catch (ApiException e) {
            msg.setCode(e.getCode());
            msg.setMessage(e.getMessage());
            msg.setRouter(dto.getString("router"));
            msg.setMethod(dto.getString("method"));
        } catch (Exception e) {
            e.printStackTrace();
            msg = new SocketMessage(ReqEnums.SYS_ERROR, dto.getString("router"),dto.getString("'method"));
        } finally {
            return  msg;
        }
    }


}
